﻿using Ec.NETCoreFramework.Common.Core;
using Ec.NETCoreFramework.Common.Core.Helpers;
using Ec.NETCoreFramework.Common.MQ;
using Ec.NETCoreFramework.Common.Core.Utilities;
using Ec.NETCoreFramework.Common.Core.Serializer;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Threading;
using System.Diagnostics;
using Ec.NETCoreFramework.Common.Plug.Core;
using Ec.NETCoreFramework.Common.Clients;

namespace MQ_WechatMoment
{
    /// <summary>
    /// 朋友圈定时拉取
    /// </summary>
    public class Moment : TaskInterface
    {
        private ConsumeConfig _consumeConfig;
        private string logTitle = "moment";
        private RequestAppSecret _appSecret;
        private string _SoftwareVersion = string.Empty;
        public override async Task ConsumeEvent(byte[] bytes)
        {

            if (_consumeConfig == null)
            {
                Console.WriteLine("对象为空");
                return;
            }
            _appSecret = new RequestAppSecret()
            {
                AppId = _consumeConfig.AppId,
                Secret = _consumeConfig.Secret
            };
            _SoftwareVersion = AppsettingsHelper.app(new string[] { "SoftwareVersion" });

            var limit = 500;
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            try
            {
                while (true)
                {
                    //从业务系统拉数据
                    var list = await PullData(limit);
                    if (list == null || list.Count == 0)
                    {
                        Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}】没有拉取到数据哟");
                        break;
                    }
                    //从微信拉数据并同步到业务系统
                    await GetMomentList(list);

                    if (list.Count < limit)
                    {
                        Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}-{_SoftwareVersion}】此次执行结束，耗时{stopwatch.ElapsedMilliseconds}ms");
                        break;
                    }
                    Thread.Sleep(1000);
                }
                stopwatch.Stop();
            }
            catch (Exception ex)
            {

                if (stopwatch.IsRunning)
                {
                    stopwatch.Stop();
                }
                Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}】:{ex.Message}");
            }
        }

        /// <summary>
        /// 从业务系统拉数据
        /// </summary>
        /// <returns></returns>
        private async Task<List<MomentOutput>> PullData(int limit)
        {
            var dic = new Dictionary<string, object>()
            {
                {"limit",limit.ToString() }
            };
            var result = await new ApiRequestClient(_appSecret).
                GetResponse<List<MomentOutput>>(_consumeConfig.Domain,
                "wxgroup.message.getmomentslastsynctime", dic);
            if (result.Success)
            {
                var ret = (IResponse<List<MomentOutput>>)result;
                return (ret.Content);
            }
            return null;

        }
        /// <summary>
        /// 从微信拉数据并同步到业务系统
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private async Task GetMomentList(List<MomentOutput> list)
        {
            foreach (var item in list)
            {
                try
                {
                    var dt_month_start = Utils.UnixTimeToTime(item.date_time.ToString(), 10);

                    var end = 0L;
                    while (DateTime.Now > dt_month_start)
                    {
                        var begin = Utils.ToUnixTime(dt_month_start,10);

                        //当前月底
                        var dt_month_end = dt_month_start.AddDays(15);
                       
                        //如果当前月最后一天大于当前时间
                        if (dt_month_end > DateTime.Now)
                        {

                            end = Utils.ToUnixTime(DateTime.Now, 10);
                        }
                        else
                        {
                            end = Utils.ToUnixTime(dt_month_end, 10);
                        }

                        await GetMomentList(item,begin,end, string.Empty);
                        dt_month_start = dt_month_end;
                    }

                    await UpdateEndTime(item, end);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"【{logTitle}】:{ex.Message};");

                }
               

            }

        }
        /// <summary>
        /// 从微信拉数据
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cursor"></param>
        /// <returns></returns>
        private async Task GetMomentList(MomentOutput item,long begin,long end, string cursor)
        {
            
            var dic = new Dictionary<string, object>()
            {
                {"fk_id",item.fk_id },
                {"db_id",item.db_id },
                {"start_time",begin },
                {"end_time",end },
                {"cursor",cursor }
            };
            var result = await new ApiRequestClient(_appSecret).
            GetResponse<JObject>(_consumeConfig.WechatDomain,
            string.Empty, dic, "/wx/moment/send/list", new Dictionary<string, string>() { { "api-version", "2.0" }, { "version", _SoftwareVersion } }, 10000);
            if (result.Success)
            {
                var re = ((IResponse<JObject>)result).Content;

                await Push(re["moment_list"] as JArray, item);


                if (re.ContainsKey("cursor"))
                {
                    cursor = re["cursor"].ToString();
                    if (!string.IsNullOrEmpty(cursor))
                    {
                        await GetMomentList(item,begin,end, cursor);
                    }
                }


            }

        }
        /// <summary>
        /// 获取客户朋友圈企业发表的列表
        /// </summary>
        /// <param name="item"></param>
        /// <param name="moment_id"></param>
        /// <param name="cursor"></param>
        /// <param name="userList"></param>
        /// <returns></returns>
        private async Task GetMomentTask(MomentOutput item, string moment_id, string cursor,List<string> userList)
        {

            var dic = new Dictionary<string, object>()
            {
                {"fk_id",item.fk_id },
                {"db_id",item.db_id },
                {"moment_id",moment_id },
                {"cursor",cursor }
            };
            var result = await new ApiRequestClient(_appSecret).
            GetResponse<JObject>(_consumeConfig.WechatDomain,
            string.Empty, dic, "/wx/moment/send/task", new Dictionary<string, string>() { { "api-version", "2.0" }, { "version", _SoftwareVersion } }, 10000);
            if (result.Success)
            {
                var re = ((IResponse<JObject>)result).Content;
                if (re.ContainsKey("task_list"))
                {
                    foreach (JObject obj in re["task_list"] as JArray)
                    {
                        userList.Add(obj["userid"].ToString());
                    }
                }

                if (re.ContainsKey("cursor"))
                {
                    cursor = re["cursor"].ToString();
                    if (!string.IsNullOrEmpty(cursor))
                    {
                        await GetMomentTask(item, moment_id, cursor, userList);
                    }
                }


            }

        }
        /// <summary>
        /// 推数据
        /// </summary>
        /// <param name="mediaOutputs"></param>
        /// <returns></returns>
        private async Task Push(JArray arr, MomentOutput item)
        {
            var list = new List<string>();
            foreach(JObject obj in arr)
            {
                if (Utils.ToInt(obj["create_type"].ToString()) == 0)
                {
                    var userList = new List<string>();
                    //获取客户朋友圈企业发表的列表
                    await GetMomentTask(item, obj["moment_id"].ToString(), string.Empty, userList);
                    obj["customer_list"] = string.Join("|", userList);
                }
                
                list.Add(Json.JsonToXml(obj, "moment").OuterXml);

            }
            var dic = new Dictionary<string, object>()
                {
                    {"fk_id",item.fk_id },
                    {"content",$"<moment_list>{string.Join("",list)}</moment_list>" }
                };
            var result = await new ApiRequestClient(_appSecret).
        PostBinary<JObject>(_consumeConfig.Domain,
        "wxgroup.message.SaveMomentResults", dic);
            if (!result.Success)
            {                
                throw new Exception(result.Message);
            }
           
        }
        /// <summary>
        /// 更新最后执行时间
        /// </summary>
        /// <param name="item"></param>
        /// <param name="end_time"></param>
        /// <returns></returns>
        private async Task UpdateEndTime(MomentOutput item, long end_time)
        {
            var dic = new Dictionary<string, object>()
                {
                    {"fk_id",item.fk_id },
                    {"lastsynctime",end_time }
                };
            var result = await new ApiRequestClient(_appSecret).
        PostBinary<JObject>(_consumeConfig.Domain,
        "wxgroup.message.setemomentslastsynctime", dic);
            if (!result.Success)
            {
                Console.WriteLine($"【{logTitle}】:{result.Message};{dic.ToLinkString()}");
            }

        }
        private string _QueueName = string.Empty;
        public override string QueueName()
        {
            return "wechat-" + _consumeConfig.MQName;
        }
        public override void SetConsumeConfig(byte[] consumeConfig)
        {
            _consumeConfig = ProtoBufSerializer.DeSerialize<ConsumeConfig>(consumeConfig);
        }
    }

}
